package com.project.service.base.CrpData;

import com.project.service.cryptolib.CryptoApp;
import com.project.utils.Base64Util;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.util.Arrays;

/**
 * author: WheelChen
 * data: 2017/7/19
 * function: 加解密文件工具类
 */
@Service
public class CryFileUtil extends CryBaseData {

    /**
     * author: WheelChen
     * date: 2017/7/19
     * function: 正在上传文件时直接加密文件
     *
     * @param all {byte[]} 上传的文件的字节流
     * @return {byte[]} 加密后的文件字节流
     */
    public byte[] encry(byte[] all) throws UnsupportedEncodingException {
        //待加密数据
        byte[] data = Arrays.copyOf(all, 24);
        System.out.println("原数据：" + Arrays.toString(data));
        //加密后的数据
        byte[] cText = CryptoApp.SM4Enc16(data, key, iv);
        System.out.println("加密后的数据" + Arrays.toString(cText));
        //加密后的数据覆盖到源文件的前16个字节
        System.arraycopy(cText, 0, all, 0, 24);
        return all;
    }

    /**
     * author: WheelChen
     * date: 2017/7/19
     * function: 解密文件
     *
     * @param path 文件路径
     * @return
     */
    public byte[] decry(String path) throws IOException {
        //准备文件
        File f = new File(path);
        //
        FileInputStream fis = new FileInputStream(f);

        byte[] all = new byte[(int) f.length()];

        fis.read(all);

        //待解密数据
        byte[] data = Arrays.copyOf(all, 24);

        System.out.println("待解密数据： " + Arrays.toString(data));
        //解密后的数据
        byte[] pText = CryptoApp.SM4Dec16(data, key, iv);

        System.out.println("解密后的数据： " + Arrays.toString(pText));

        System.arraycopy(pText, 0, all, 0, 24);

        return all;
    }

    /**
     * author: WheelChen
     * date: 2017/8/7
     * function: 解密文件并转为base64格式
     *
     * @param path 文件绝对路径
     * @return
     */
    public String decrypted(String path) throws IOException {
        File f = new File(path);

        FileInputStream fis = new FileInputStream(f);

        byte[] all = new byte[(int) f.length()];

        fis.read(all);

        String base64 = Base64Util.encode(decry(path));

        return base64;
    }
}
